#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <queue>
#define maxn 305
#define GRASS '.'
#define BAR '#'
#define OUTLET '='
#define INLET '@'
using namespace std;
int N, M, x, y, t;
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
char map[maxn][maxn], vis[maxn][maxn];
struct point
{
    int x, y, t;
    point(int x = 0, int y = 0, int t = 0) : x(x), y(y), t(t){};
    bool operator==(point p) { return (x == p.x && y == p.y); };
};
point inlet, outlet, now;
point find(point p)
{
    int x = p.x, y = p.y, t = p.t;
    char ch = map[x][y];
    for (int x = 0; x < N; x++)
        for (int y = 0; y < M; y++)
            if (ch == map[x][y] && (x != p.x || y != p.y) && vis[x][y] == 0)
                return point(x, y, t);
    return p;
}
queue<point> qu;
char ch;
int main()
{
    cin >> N >> M;
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < M; ++j)
        {
            while ((ch = getchar()) == '\n')
                ;
            if (ch == INLET)
                inlet = point(i, j);
            if (ch == OUTLET)
                outlet = point(i, j);
            if (ch == BAR)
                vis[i][j] = 1;
            map[i][j] = ch;
        }
    }
    qu.push(inlet);
    vis[inlet.x][inlet.y] = 1;
    while (!qu.empty())
    {
        now = qu.front();
        qu.pop();
        if (now == outlet)
            break;
        x = now.x, y = now.y, t = now.t;
        for (int i = 0; i < 4; ++i)
        {
            int tx = x + dx[i], ty = y + dy[i];
            if (tx >= 0 && ty >= 0 && tx < N && ty < M && vis[tx][ty] == 0)
            {
                if (map[tx][ty] >= 'A' && map[tx][ty] <= 'Z')
                {
                    point tmp = find(point(tx, ty));
                    tx = tmp.x, ty = tmp.y;
                }
                else
                    vis[tx][ty] = 1;
                qu.push(point(tx, ty, t + 1));
            }
        }
    }
    cout << now.t << endl;
    return 0;
}